<template>
  <el-card>
    <el-form :model="searchParam" :inline="true">
      <el-form-item label="用户账号">
        <el-input
          placeholder="请输入用户账号"
          clearable
          v-model="searchParam.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input
          placeholder="请输入手机号"
          clearable
          v-model="searchParam.phoneNumber"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <commonBtn
          :value="'搜索'"
          :type="'primary'"
          :icon="'search'"
          :plain="true"
          @click="getTableData"
        ></commonBtn>
        <commonBtn
          :value="'重置'"
          :icon="'refresh'"
          @click="refreshFn"
        ></commonBtn>
      </el-form-item>
    </el-form>
    <el-row>
      <commonBtn
        :value="'添加用户'"
        :type="'primary'"
        :icon="'plus'"
        :plain="true"
        @click="addSelectFn"
      ></commonBtn>
      <commonBtn
        :value="'批量取消授权'"
        :icon="'circle-close'"
        :type="'danger'"
        :plain="true"
        :disabled="ids.length === 0"
        @click="cancelUserFn"
      ></commonBtn>
      <commonBtn
        :value="'返回上一层'"
        :type="'warning'"
        :icon="'close'"
        :plain="true"
        @click="backFn"
      ></commonBtn>
    </el-row>
    <el-table
      :data="searchParam.data"
      v-loading="isLoad"
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" class="center" />
      <el-table-column label="用户账号" prop="username"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column label="手机号" prop="phoneNumber"></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status == '0'">{{
            scope.row.statusDict
          }}</el-tag>
          <el-tag type="danger" v-if="scope.row.status == '1'">{{
            scope.row.statusDict
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template #default="scope">
          <el-button type="text" link @click="cancelOneFn(scope.row.userId)">
            <i class="el-icon-circle-close"></i> 取消授权</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pag
      :showPage="true"
      :pageData="searchParam"
      @getTableData="getTableData"
    />
    <selectUser :layer="layer" :roleId="searchParam.roleId" v-if="layer.show"></selectUser>
  </el-card>
</template>
<script lang="js">
import commonBtn from "_c/commonBtn/index.vue";
import { defineComponent, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { queryByRoleId } from "@/api/user.js";
import pag from "_c/pag/index.vue";
import { cancelUser } from "@/api/role.js";
import { ElMessage, ElMessageBox } from "element-plus";
import selectUser from "./select-user.vue";
export default defineComponent({
  components: { commonBtn, pag, selectUser },
  setup() {
    // 弹窗控制器
    const layer = reactive({
      show: false,
      title: "",
      showButton: true,
      width: 800
    });
    //需要删除的ids
    const ids = ref([]);
    //表格引用
    const multipleTableRef = ref(null);
    //路由
    const route = useRoute();
    const router = useRouter();
    //查询条件
    const searchParam = reactive({
      username: "",
      phoneNumber: "",
      roleId: "",
      data: [],
      current: 1, //页码
      size: 10, //每页显示条数
      total: 0, //数据总数
    });
    //表格懒加载
    const isLoad = ref(true);
    //挂载时，获取路由参数
    const init = () => {
      let roleId = route.query.id;
      if (roleId) {
        localStorage.setItem("roleId", roleId);
      } else {
        roleId = localStorage.getItem("roleId");
      }
      searchParam.roleId = roleId;

      getTableData();
    };
    //查询列表数据
    const getTableData = async () => {
      let params = {
        pageNum: searchParam.current,
        pageSize: searchParam.size,
        username: searchParam.username || undefined,
        roleId: searchParam.roleId,
        phoneNumber: searchParam.phoneNumber || undefined,
      };
      const { data, success } = await queryByRoleId(params);
      if (success) {
        searchParam.data = data.records;
        searchParam.total = parseInt(data.total);
      }
      isLoad.value = false;
    };
    //表单重置
    const refreshFn = () => {
      searchParam.username = "";
      searchParam.phoneNumber = "";
      getTableData();
    };
    //多选处理
    const handleSelectionChange = (val) => {
      ids.value = [];
      if (val) {
        if (val.length > 0) {
          for (let i = 0; i < val.length; i++) {
            ids.value.push(val[i]["userId"]);
          }
        }
      }
    };
    //调用取消授权
    const cancel = async () => {
      console.log(ids.value);
      let data = {
        roleId: searchParam.roleId,
        userIds: ids.value,
      };
      const { success } = await cancelUser(data);
      if (success) {
        ElMessage.success("操作成功！");
        getTableData();
      }
    };
    //批量取消授权
    const cancelUserFn = () => {
      if (ids.value.length === 0) {
        return;
      }
      ElMessageBox.confirm("您确认要取消授权吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          cancel();
        })
        .catch(() => {
          multipleTableRef.value.clearSelection();
          ElMessage.info("已取消！");
        });
    };
    //单个取消授权
    const cancelOneFn = (userId) => {
      if (!userId) {
        return;
      }
      ElMessageBox.confirm("您确认要取消授权吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ids.value = [];
          ids.value.push(userId);
          cancel();
        })
        .catch(() => {
          ids.value = [];
          ElMessage.info("已取消！");
        });
    };
    //回退角色管理
    const backFn = () => {
      router.replace("/pages/role");
    };
    //展示弹框
    const addSelectFn = () => {
      layer.title = "选择用户";
      layer.show = true;
      delete layer.row;
    };
    init();
    return {
      layer,
      ids,
      multipleTableRef,
      searchParam,
      isLoad,
      getTableData,
      refreshFn,
      handleSelectionChange,
      cancelUserFn,
      cancelOneFn,
      backFn,
      addSelectFn,
    };
  },
});
</script>
<style>
.el-form {
  display: flex;
  justify-content: left;
}
.el-table {
  margin-top: 15px;
}
</style>
